<template>
  <div id="make_knowledgeDetail">
    <div
      v-if="roles === 'teacher' || roles === 'internet_admin'"
      class="one-btns"
    >
      <div class="title">知识库结构图</div>
      <div class="all-btn" @click="generateChapterFn()">
        生成章节并同步教学知识点
      </div>
    </div>
    <!-- 树形图 -->
    <div class="content">
      <div class="graph-tree">
        <el-tree
          ref="tree"
          :data="treeData"
          show-checkbox
          node-key="id"
          default-expand-all
          :check-on-click-node="false"
          :expand-on-click-node="false"
          :props="defaultProps"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node" @click.stop>
              <div class="tree-node-name" @click.stop="nodeClick(data)">
                <span>{{ node.label }}</span>
                <span v-show="data.flag" class="yinaru">
                  <el-icon :size="13" color="#3cb41a"><CircleCheck /></el-icon>
                </span>
                <span v-show="!data.flag" class="weinaru"></span>
              </div>
              <div class="tree-node-btn">
                <el-button type="primary" link @click="appendNode(data)">
                  <el-icon :size="12" color="#457aff"><CirclePlus /></el-icon>
                  新增
                </el-button>
                <el-button type="primary" link @click="editNode(data)">
                  <el-icon :size="12" color="#457aff"><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button
                  style="margin-left: 4px"
                  type="primary"
                  link
                  @click.stop="removeNode(node, data)"
                >
                  <el-icon :size="12" color="#457aff"><Close /></el-icon>
                  删除
                </el-button>
              </div>
            </div>
          </template>
        </el-tree>
      </div>
      <div class="graph-form">
        <!-- 暂无节点状态 -->
        <div v-show="!showEditForm" class="no-node">
          <span>暂无节点</span>
        </div>

        <!-- 编辑表单状态 -->
        <div v-show="showEditForm" class="edit-form">
          <div class="node-name">
            <span>名称</span>
            <el-input
              v-model="form.nodeName"
              maxlength="20"
              show-word-limit
              :disabled="!isEdit"
            />
          </div>
          <div class="node-knowledge">
            <span>知识点</span>
            <MdEditor
              ref="mdEditor"
              :key="editorKey"
              v-model="form.nodeKnowledge"
              :toolbars="isEdit ? toolbars : []"
              :footers="[]"
              :disabled="!isEdit"
              class="knowledge-editor"
              :class="[
                isEdit ? 'md-editor-edit-only' : 'md-editor-preview-only',
              ]"
              :maxLength="50000"
            />
          </div>
          <div class="form-buttons">
            <el-button class="saveBtn" @click="saveNode()">保存</el-button>
            <el-button class="cancelBtn" @click="cancelEdit()">取消</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 同步知识点弹窗 -->
    <el-dialog
      center
      class="syncKnowledgeDialog"
      v-model="showSyncKnowledgeDialog"
      width="35%"
      :close-on-click-modal="false"
      :before-close="() => (showSyncKnowledgeDialog = false)"
    >
      <div class="body-content">
        <img src="@/assets/img/ai助手.png" alt="" />
        <div class="body-text">
          <p>
            如果内容与已采纳的章节知识存在重复，为避免信息冗余，建议您选择一下操作：
          </p>
          <p><b>更新知识点：</b>覆盖原有内容并补充新细节</p>
          <p><b>跳过知识点：</b>忽略本次内容</p>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button color="#155EEF" @click="updateAndJumpKnowledge('1')">
            更新知识点</el-button
          >
          <el-button color="#155EEF" @click="updateAndJumpKnowledge('2')"
            >跳过知识点</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>
    
<script>
import HomeChart2 from "@/components/HomeChart2.vue";
export default {
  components: {
    HomeChart2,
  },
  name: "ZhishiIndex",
  data() {
    return {
      courseId: "",
      knowledgeId: "",
      bookId: "",
      kbId: "",
      roles: "",
      showSyncKnowledgeDialog: false,
      showEditForm: false,
      form: {
        nodeName: "",
        nodeKnowledge: "",
        parentId: "",
        nodeId: "",
      },
      isEdit: false,
      isAdd: false,
      editorKey: 0, // 添加编辑器key，用于强制重新渲染
      rules: {
        nodeName: [{ required: true, message: "请输入名称", trigger: "blur" }],
        nodeKnowledge: [
          { required: true, message: "请输入知识点", trigger: "blur" },
        ],
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      treeData: [],
      treeSelects: [], // 选中节点
      toolbars: [
        "bold",
        "underline",
        "italic",
        "strikeThrough",
        "katex",
        "link",
        "image",
        "table",
        "preview",
      ],
    };
  },
  created() {
    this.roles = JSON.parse(localStorage.getItem("userInfo")).roles[0];
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.knowledgeId = this.$route.query.id;
    this.kbId = Number(this.$route.query.kbId);
    this.getTreeData();
  },
  methods: {
    // 获取知识库tree列表
    getTreeData() {
      this.$axios
        .get(`/tes/course/auto/make/getDirectoryTree?kbId=${this.kbId}`)
        .then((res) => {
          this.treeData = res.data;
          this.bookId = res.data[0].bookId;
        });
    },

    generateChapterFn() {
      this.treeSelects = this.$refs.tree.getCheckedNodes();
      const halfCheckedNodes = this.$refs.tree.getHalfCheckedNodes(); // 半选节点
      const allSelectedNodes = [...this.treeSelects, ...halfCheckedNodes];
      const resObj = this.filterChecked(allSelectedNodes);
      console.log("resObj", resObj);
      if (resObj.length === 0) {
        this.$message.warning("请先选择树形节点");
        return;
      }
      this.showSyncKnowledgeDialog = true;
    },

    // 节点点击查看
    nodeClick(data) {
      this.isEdit = false;
      this.showEditForm = true;
      this.editorKey++; // 强制重新渲染编辑器，避免预览模式冲突
      const loading = this.$loading({
        lock: true,
        text: "加载中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.form.nodeName = data.label;
      this.form.nodeId = data.id;
      this.form.parentId = data.parentId;
      this.$axios
        .get(`/tes/course/auto/make/getDirectoryTreeMarkdown?id=${data.id}`)
        .then((res) => {
          this.$nextTick(() => {
            this.form.nodeKnowledge = res.data;
          });
        })
        .finally(() => {
          loading.close();
        });
    },

    // 新增节点
    appendNode(data) {
      this.form.nodeName = "";
      this.form.nodeKnowledge = "";
      this.form.parentId = data.id;
      this.form.nodeId = data.id;
      this.isEdit = true;
      this.showEditForm = true;
      this.isAdd = true;
      this.editorKey++; // 强制重新渲染编辑器，确保新增模式正确显示
    },

    // 编辑节点
    editNode(data) {
      this.isEdit = true;
      this.isAdd = false;
      this.showEditForm = true;
      this.editorKey++; // 强制重新渲染编辑器，确保编辑模式正确显示
      const loading = this.$loading({
        lock: true,
        text: "加载中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.form.nodeName = data.label;
      this.form.nodeId = data.id;
      this.form.parentId = data.parentId;
      this.$axios
        .get(`/tes/course/auto/make/getDirectoryTreeMarkdown?id=${data.id}`)
        .then((res) => {
          this.form.nodeKnowledge = res.data;
        })
        .finally(() => {
          loading.close();
        });
    },

    // 保存新增/修改节点
    saveNode() {
      let queryObj = {};
      if (this.isAdd) {
        queryObj = {
          kbId: this.kbId,
          parentId: this.form.parentId,
          name: this.form.nodeName,
          content: this.form.nodeKnowledge,
        };
      } else {
        queryObj = {
          kbId: this.kbId,
          parentId: this.form.parentId,
          id: this.form.nodeId,
          name: this.form.nodeName,
          content: this.form.nodeKnowledge,
        };
      }
      this.$axios
        .put(`/tes/course/auto/make/updateDirectoryTreeMarkdown`, queryObj)
        .then((res) => {
          this.$message.success("保存成功");
          this.getTreeData();
          this.cancelEdit();
        });
    },

    // 删除节点
    removeNode(node, data) {
      this.$confirm("确定删除该节点吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios
          .delete(
            `/tes/course/auto/make/deleteDirectoryTree?kbId=${this.kbId}&nodeId=${data.id}`
          )
          .then((res) => {
            this.$message.success("删除成功");
            this.getTreeData();
          });
      });
    },

    // 取消编辑
    cancelEdit() {
      this.showEditForm = false;
      this.form = {
        nodeName: "",
        nodeKnowledge: "",
        parentId: "",
        nodeId: "",
      };
      this.isEdit = false;
      this.editorKey++; // 重置编辑器状态
    },

    // 更新知识点并跳转
    updateAndJumpKnowledge(type) {
      this.treeSelects = this.$refs.tree.getCheckedNodes();
      const halfCheckedNodes = this.$refs.tree.getHalfCheckedNodes(); // 半选节点
      const allSelectedNodes = [...this.treeSelects, ...halfCheckedNodes];
      const resObj = this.filterChecked(allSelectedNodes);
      console.log("resObj", resObj);

      const queryObj = {
        bookId: this.bookId,
        chapterTypeStr: "理论课",
        treeSelects: resObj,
      };
      const loading = this.$loading({
        lock: true,
        text: "加载中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$axios
        .post(
          `/tes/course/book/directory/chapter/continueMergeChapter/${this.courseId}?type=${type}`,
          queryObj
        )
        .then((res) => {
          if (res && res.code == 200) {
            this.$message.success("更新成功");
            this.$router.push("/aiTeaching/courseBuild/makeCourseChapter");
          }
        })
        .finally(() => {
          loading.close();
        });

      this.showSyncKnowledgeDialog = false;
    },

    // 过滤选中节点
    filterChecked(checked) {
      // 获得选中集合的node-key
      const indexCodeList = checked.map(function (item) {
        return item.id;
      });

      // 判断node-key是否含有parent-key
      checked.map((value, index) => {
        if (indexCodeList.indexOf(value.parentId) !== -1) {
          checked.splice(index, 1, 1);
        }
      });
      this.treeSelects = checked.filter((value) => {
        return value !== 1;
      });

      // 基于原始treeData来过滤，保持原有顺序
      const filteredTree = this.filterTreeByIds(this.treeData, indexCodeList);
      return filteredTree;
      // return this.treeSelects
    },
    filterTreeByIds(tree, selectedIds) {
      return tree
        .map((node) => {
          // 复制节点对象
          const filteredNode = { ...node };

          // 检查子节点是否存在并递归过滤
          if (filteredNode.children && filteredNode.children.length) {
            filteredNode.children = this.filterTreeByIds(
              filteredNode.children,
              selectedIds
            );
          }

          // 如果当前节点或其子节点在选中列表中，保留该节点
          if (
            selectedIds.includes(filteredNode.id) ||
            (filteredNode.children && filteredNode.children.length)
          ) {
            return filteredNode;
          }

          // 如果当前节点和子节点都不在选中列表中，过滤掉该节点
          return null;
        })
        .filter(Boolean);
    },
  },
};
</script>
<style lang="scss" scoped>
#make_knowledgeDetail {
  width: 100%;
  background-color: #f3f5fa;
  padding: 20px 30px;
  box-sizing: border-box;
  overflow-x: hidden;
  .one-btns {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    .title {
      font-size: 18px;
      color: #596184;
    }
  }
  .content {
    height: 100%;
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    .graph-tree {
      padding: 30px;
      overflow-y: auto;
      width: calc(50% - 10px);
      height: 600px;
      background: #ffffff;
      border-radius: 10px;
      box-sizing: border-box;
    }
    .graph-form {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      padding: 50px 40px;
      width: calc(50% - 10px);
      height: 600px;
      background: #ffffff;
      border-radius: 10px;
      box-sizing: border-box;

      .no-node {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        span {
          font-size: 16px;
          color: #999;
        }
      }

      .edit-form {
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 100%;
        overflow: hidden;
      }
      .node-name {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        width: 100%;
        margin-bottom: 20px;
        span {
          flex-shrink: 0;
          font-size: 14px;
          color: #596184;
          margin-bottom: 13px;
        }
      }
      .node-knowledge {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        width: 100%;
        margin-bottom: 20px;
        flex: 1;
        span {
          flex-shrink: 0;
          font-size: 14px;
          color: #596184;
          margin-bottom: 13px;
        }

        .knowledge-editor {
          width: 100%;
          height: 100% !important;
          max-height: 300px;

          // 预览
          &.md-editor-preview-only {
            :deep(.md-editor-input-wrapper) {
              display: none !important;
            }
            :deep(.md-editor-content) {
              width: 100% !important;
              height: 100% !important;
              overflow-y: auto;
            }
            :deep(.md-editor-preview-wrapper) {
              overflow: visible;
            }
            :deep(.md-editor-resize-operate) {
              display: none !important;
            }
          }

          // 编辑
          &.md-editor-edit-only {
            :deep(.md-editor-resize-operate) {
              display: none !important;
            }
          }
        }
      }
      .form-buttons {
        display: flex;
        align-items: center;
        margin-top: 20px;
        flex-shrink: 0;
      }

      .saveBtn {
        background-color: #155eef;
        color: #fff;
      }

      .cancelBtn {
        background-color: #f5f7fa;
        color: #606266;
        border: 1px solid #dcdfe6;
      }
    }
    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
      .tree-node-name {
        display: flex;
        align-items: center;
        gap: 10px;
        .weinaru {
          width: 12px;
          height: 12px;
          background-color: #e6dede;
          border-radius: 50%;
        }
        .yinaru {
        }
      }

      // 默认隐藏操作按钮
      .tree-node-btn {
        opacity: 0;
        transition: opacity 0.2s ease-in-out;
      }

      // 鼠标悬停时显示操作按钮
      &:hover .tree-node-btn {
        opacity: 1;
      }
    }
  }
  .all-btn {
    display: inline-flex;
    justify-content: center;
    align-items: center;
    gap: 4px;
    height: 40px;
    line-height: 40px;
    background: #457aff;
    border-radius: 4px;
    font-size: 14px;
    color: #fff;
    padding: 0 18px;
    cursor: pointer;
  }

  .syncKnowledgeDialog {
    .body-content {
      display: flex;
      align-items: flex-start;
      justify-content: center;
      padding: 30px 0;
      .body-text {
        margin-left: 10px;
        p {
          font-size: 14px;
          color: #596184;
          margin-bottom: 10px;
          margin-top: 0;
          b {
            color: #155eef;
          }
        }
      }
    }
  }
}
</style>